# GID Importer for UIDs for PermFS

import pwd

GROUPPATH = '/etc/group'
CACHE = False

class GIDImporter:
    def __init__(self):
        self.group = open(GROUPPATH, 'r')
        if CACHE:
            self.gidmap = self.get_all_gids()

    def close(self):
        self.group.close()

    def get_all_gids(self):
        gidmap = { }

        for line in self.group:
            line = line.strip().split(":")
            users = line[3]
            if users:
                for user in users.split(","):
                    try:
                        uid = pwd.getpwnam(user).pw_uid
                        if not uid in gidmap:
                            gidmap[uid] = [pwd.getpwnam(user).pw_gid]
                        if int(line[2]) != gidmap[uid][0]:
                            gidmap[uid].append(int(line[2]))
                    except KeyError:
                        continue
        self.group.seek(0)
        return gidmap

    def get_gids(self, uid):
        try:
            if CACHE:
                return self.gidmap[uid]

            passwd_struct = pwd.getpwuid(uid)
            uname = passwd_struct.pw_name
            gids = [passwd_struct.pw_gid]

            for line in self.group:
                line = line.strip().split(":")
                users = line[3]
                if users:
                    for user in users.split(","):
                        if user == uname and int(line[2]) != gids[0]:
                            gids.append(int(line[2]))
                            break
            self.group.seek(0)
            return gids
        except KeyError:
            return []

